/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;


import Traductor.parsero;
import com.nilo.plaf.nimrod.NimRODLookAndFeel;
import com.nilo.plaf.nimrod.NimRODTheme;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import Optimizacion.*;
import Traductor.lexo;
import java.io.InputStreamReader;

/**
 *
 * @author REI
 */
public class Traductor extends javax.swing.JFrame {

    /**
     * Creates new form Principal
     */
    EditorTexto tab;
    String salida;
    File archivoaux;
    File archivonivel;
    File archivoenemigo;
    File archivojugador;
    Optimizador optimiza;
    EditorAssembler editorasm;
    String archivoasm;
    
    ///traductor
    public int normal = 0;
    
    public Traductor() {
        
        setDefaultLookAndFeelDecorated(true);
        setBackground(Color.WHITE);
        try {

            NimRODTheme tema = new NimRODTheme("src/Temas/NimRODThemeFile1.theme");
            NimRODLookAndFeel milook = new NimRODLookAndFeel();

            NimRODLookAndFeel.setCurrentTheme(tema);
            UIManager.setLookAndFeel(milook);



        }catch (Exception e) {
            System.out.println(e);
        }
        initComponents();
        optimiza = new Optimizador();
        editorasm = new EditorAssembler();
        editorasm.jTextArea1.setEditable(false);
        archivoasm ="";

    }
    
    public void AbrirArchivos()
    {
        boolean cargado = false;
        String[] patharchivo = null;
        JFileChooser choosercargar = new JFileChooser();
        choosercargar.setFileFilter(new Filtro("cpp", "archivo *.cpp"));



        choosercargar.showOpenDialog(this);


        if (choosercargar.getSelectedFile() != null) {
            salida = choosercargar.getSelectedFile().getAbsolutePath();
            File f = new File(salida);
            if (!f.exists()) {


                JOptionPane.showMessageDialog(null, "No Selecciono un Archivo");    //No existe
                } else {
                cargado = true;
                patharchivo = new String[2];
                patharchivo[0]=f.getName();
                patharchivo[1]=salida;
            }
        }// final del if

        if (cargado == true) {

            try {


                if (patharchivo != null && estaAbierto(patharchivo) ) {
                File archivo = null;
                BufferedReader entrada = null;
                String lectura = "";
                String contenido = "";
                archivo = new File(patharchivo[1].trim());
                contenido = "";
                if (archivo.getName().toLowerCase().endsWith(".cpp")) {
                    try {
                        entrada = new BufferedReader(new FileReader(archivo));
                    } catch (FileNotFoundException ex) {
                        System.out.println("no se puede leer el archivo");
                    }
                    try {
                        lectura = entrada.readLine();
                        while (lectura != null) {
                            contenido = contenido + lectura + "\n";
                            lectura = entrada.readLine();
                        }
                    } catch (IOException ex) {
                        System.out.println("fallo el buffer de lectura");
                    }


                      tab  = new EditorTexto();
                      tab.Inicializar(patharchivo[0],patharchivo[1], contenido);                      
                      Tabbs.add(patharchivo[0], tab);
                      Tabbs.setSelectedIndex(Tabbs.getTabCount()-1);


                }

            }




            }catch (Exception ex) {
                ex.printStackTrace();

        }


        } else {

            
        }
    }
    
    public boolean estaAbierto(String[] path) {

        EditorTexto temp;
        String paths = "";
        for (int i = 0; i < Tabbs.getTabCount(); i++) {
            temp = (EditorTexto ) Tabbs.getComponentAt(i);
            paths = temp.getPath();
            if (paths.compareTo(path[1]) == 0) {
                Tabbs.setSelectedIndex(i);
                return false;
            }
        }
        return true;
    }
    
    public void GuardarArchivo(String path, String contenido) {
        File archivo = null;
        BufferedWriter escribir = null;

        try {
            archivo = new File(path);
            escribir = new BufferedWriter(new FileWriter(archivo));

            if (contenido != null) {
                escribir.write(contenido);

                }
            escribir.close();
        } catch (IOException ex) {
        }
    }
    
    public void Guardar()
    {
        if(Tabbs.getComponentCount()!=0)
         {
        EditorTexto aux = (EditorTexto)Tabbs.getComponentAt(Tabbs.getSelectedIndex());

         if(aux!=null)
         {
            GuardarArchivo(aux.getPath(), aux.getContenido());
         }
         }
    }
    
    public void Copiar()
    {
         if(Tabbs.getComponentCount()!=0)
         {
        EditorTexto aux = (EditorTexto)Tabbs.getComponentAt(Tabbs.getSelectedIndex());

         if(aux!=null)
         {
            aux.copiar();
         }
         
         }
    }
    
    public void Pegar()
    {
        if(Tabbs.getComponentCount()!=0)
         {
        EditorTexto aux = (EditorTexto)Tabbs.getComponentAt(Tabbs.getSelectedIndex());

         if(aux!=null)
         {
            aux.pegar();
         }
         }
    }
    
    public void GuardarComo()
    {
        if(Tabbs.getComponentCount()!=0)
         {
        String miarchivo;
        String ext;
        JFileChooser choosercargar = new JFileChooser();
        choosercargar.setFileFilter(new Filtro("ejecutable", "archivo *.cpp"));
        

        choosercargar.showSaveDialog(this);
        
        if (choosercargar.getSelectedFile() != null) {
            miarchivo = choosercargar.getSelectedFile().getAbsolutePath();

            ext = choosercargar.getFileFilter().getDescription();
            ext = ext.substring(ext.length()-4, ext.length());
            
            
            if(Tabbs.getComponentCount()!=0)
            {
                 EditorTexto aux = (EditorTexto)Tabbs.getComponentAt(Tabbs.getSelectedIndex());
                 if(aux!=null)
                 {
                    GuardarArchivo(miarchivo+ext, aux.getContenido());
                 }
            }
            
             
            
            
        }
        else
        {
             JOptionPane.showMessageDialog(null, "No Selecciono un Archivo");    //No existe
        }
        
        }
            
    }
    
    public File Abrir(String extension)
    {
        File archivo = null;
        String path;
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new Filtro(extension,"archivo *."+extension));
        chooser.showOpenDialog(this);
        
        if(chooser.getSelectedFile()!=null)
        {
            path = chooser.getSelectedFile().getAbsolutePath();
            archivo = new File(path);
            if(archivo.exists())
            {
                return archivo;
            }
            else
            {
                return archivo;
            }
        }
        
        return archivo;
    }
    
    public void Optimizar()
    {   if(Tabbs.getComponentCount()!=0)
         {
        boolean optimizacion = false;
        EditorTexto aux = (EditorTexto)Tabbs.getComponentAt(Tabbs.getSelectedIndex());
        parsero miparser;
        File f;

         if(aux!=null)
         {
            f = new File(aux.getPath());
            try {
                optimiza.IniciarOptimizacion(f);
//                miparser = new parsero(new lexo(new FileInputStream(f)));
//                miparser.parse();
                optimizacion = true;
                
            }catch (Exception ex) {
                optimizacion = false;
                JOptionPane.showMessageDialog(this,"Se produjo un error en la optimizacion\n por favor verifique el codigo");
                Logger.getLogger(Traductor.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            
            if(optimizacion)
            {
                System.out.println("optimizado");
            }
            
            
         }
         
         }
        
    }

    public void Analizar()
    {
        if(Tabbs.getComponentCount()!=0)
         {
        
        EditorTexto aux = (EditorTexto)Tabbs.getComponentAt(Tabbs.getSelectedIndex());
        analizador miparser;
        File f;
        Guardar();
         if(aux!=null)
         {
            f = new File(aux.getPath());
            try {
                miparser = new analizador(new FileInputStream(f));
                miparser.iniciar();


            } catch (FileNotFoundException ex) {
                Logger.getLogger(Traductor.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(Traductor.class.getName()).log(Level.SEVERE, null, ex);
            }
         }
         
         }

    }
    
    public String ObtenerPath(String dire)
    {
        String direccion="";
        String diraux;        
        diraux = dire.replace("\\", "//");
        String dir[];
        dir = diraux.split("//");
             
        for(int i=0; i < dir.length -1; i++)
        {
            direccion = direccion + dir[i] + "\\";
        }
        
        return direccion;
    }

    public void cargarCodigoAsm()
    {
        File f = new File(archivoasm);
        boolean cargado = false;
        if(f.exists())
        {
//            parsera parserasm = null;
//            try {
//                parserasm = new parsera(new lexa(new FileInputStream(f)));
//                parserasm.parse();
//                cargado = true;
//
//            } catch (Exception ex) {
//                cargado = false;
//                Logger.getLogger(Traductor.class.getName()).log(Level.SEVERE, null, ex);
//            }
//
//            if(cargado)
//            {
//                inicializarTraductor(parserasm);
//                ejecutar(false);
//            }
            
        }
        
    }
    
    public String ObtenerDireccion(String dire, String nombre)
    {
        String direccion;
        String diraux; 
        int tamañoDir = dire.length();
        int tamañoNom = nombre.length();
        
        diraux = dire.substring(0, tamañoDir - tamañoNom);
        direccion = diraux;
        
        return direccion;
    }
    public void compilarCpp(String nombre, String nombre2)
    {
        String entrada = null;
        String nombreObj = nombre2.replace(".cpp","");

            try {
            String comando = "g++ -o "+nombreObj+" "+nombre;
            Process p = Runtime.getRuntime().exec(comando);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // Leemos la salida del comando y la desplegamos en el jTextArea
            while ((entrada = stdInput.readLine()) != null) {
            consola.append(entrada+"\n");
            }

            // Leemos los errores si los hubiera y la desplegamos en el jTextArea
            while ((entrada = stdError.readLine()) != null) {
            consola.append(entrada+"\n");
            }
            } catch (IOException e) {
            System.out.println("Excepción: ");
            } 
    }
    
    public void ejecutarCpp(String path , String nombre)
    {
        String entrada = null;
        String nombreObj = nombre.replace(".cpp","");
        String direccion = ObtenerDireccion(path, nombre);
        Process p;
        String comando;

            try {
            comando = "./"+nombreObj;
            System.out.println("cd "+direccion+"\n"+comando);
            p = Runtime.getRuntime().exec(comando);
            System.out.println("despues de comando");
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // Leemos la salida del comando y la desplegamos en el jTextArea
            while ((entrada = stdInput.readLine()) != null) {
            consola.append(entrada+"\n");
            }

            // Leemos los errores si los hubiera y la desplegamos en el jTextArea
            while ((entrada = stdError.readLine()) != null) {
            consola.append(entrada+"\n");
            }
            } catch (IOException e) {
            System.out.println("Excepción: ");
            } 
    }
    
    public void MostrarResultados()
    {
         
         if(Tabbs.getComponentCount()!=0)
         {
             EditorTexto aux = (EditorTexto)Tabbs.getComponentAt(Tabbs.getSelectedIndex());

             if(aux!=null)
             {
                 consola.setText("");
                 compilarCpp(aux.getPath(),aux.getNombre());
                 ejecutarCpp(aux.getPath(),aux.getNombre());
             }
         }
    
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        btabrir = new javax.swing.JButton();
        btguardar = new javax.swing.JButton();
        btguardarcomo = new javax.swing.JButton();
        btcopiar = new javax.swing.JButton();
        btpegar = new javax.swing.JButton();
        btcompilar = new javax.swing.JButton();
        btejecutar = new javax.swing.JButton();
        Tabbs = new javax.swing.JTabbedPane();
        jScrollPane6 = new javax.swing.JScrollPane();
        consola = new javax.swing.JTextArea();

        jToolBar1.setRollover(true);

        btabrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/open.png"))); // NOI18N
        btabrir.setToolTipText("Abrir");
        btabrir.setFocusable(false);
        btabrir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btabrir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btabrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btabrirActionPerformed(evt);
            }
        });
        jToolBar1.add(btabrir);

        btguardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
        btguardar.setToolTipText("guardar");
        btguardar.setFocusable(false);
        btguardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btguardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btguardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btguardarActionPerformed(evt);
            }
        });
        jToolBar1.add(btguardar);

        btguardarcomo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/filesaveas.png"))); // NOI18N
        btguardarcomo.setToolTipText("Guardar Como..");
        btguardarcomo.setFocusable(false);
        btguardarcomo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btguardarcomo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btguardarcomo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btguardarcomoActionPerformed(evt);
            }
        });
        jToolBar1.add(btguardarcomo);

        btcopiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/copy.png"))); // NOI18N
        btcopiar.setToolTipText("Copiar");
        btcopiar.setFocusable(false);
        btcopiar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btcopiar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btcopiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btcopiarActionPerformed(evt);
            }
        });
        jToolBar1.add(btcopiar);

        btpegar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/paste.png"))); // NOI18N
        btpegar.setToolTipText("Pegar");
        btpegar.setFocusable(false);
        btpegar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btpegar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btpegar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btpegarActionPerformed(evt);
            }
        });
        jToolBar1.add(btpegar);

        btcompilar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/optimization.png"))); // NOI18N
        btcompilar.setToolTipText("optimizar");
        btcompilar.setFocusable(false);
        btcompilar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btcompilar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btcompilar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btcompilarActionPerformed(evt);
            }
        });
        jToolBar1.add(btcompilar);

        btejecutar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/run.png"))); // NOI18N
        btejecutar.setToolTipText("ejecutar");
        btejecutar.setFocusable(false);
        btejecutar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btejecutar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btejecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btejecutarActionPerformed(evt);
            }
        });
        jToolBar1.add(btejecutar);

        consola.setColumns(20);
        consola.setRows(5);
        jScrollPane6.setViewportView(consola);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 1009, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(Tabbs, javax.swing.GroupLayout.DEFAULT_SIZE, 1009, Short.MAX_VALUE)))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Tabbs, javax.swing.GroupLayout.DEFAULT_SIZE, 510, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Editor Codigo 3D", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 688, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btcompilarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btcompilarActionPerformed
        // TODO add your handling code here:
        Guardar();
        Optimizar();
    }//GEN-LAST:event_btcompilarActionPerformed

    private void btpegarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btpegarActionPerformed
        // TODO add your handling code here:
        Pegar();
    }//GEN-LAST:event_btpegarActionPerformed

    private void btcopiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btcopiarActionPerformed
        // TODO add your handling code here:
        Copiar();
    }//GEN-LAST:event_btcopiarActionPerformed

    private void btguardarcomoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btguardarcomoActionPerformed
        // TODO add your handling code here:
        GuardarComo();
    }//GEN-LAST:event_btguardarcomoActionPerformed

    private void btguardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btguardarActionPerformed
        // TODO add your handling code here:
        Guardar();
    }//GEN-LAST:event_btguardarActionPerformed

    private void btabrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btabrirActionPerformed
        // TODO add your handling code here:
        AbrirArchivos();
    }//GEN-LAST:event_btabrirActionPerformed

    private void btejecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btejecutarActionPerformed
        // TODO add your handling code here:
//        Guardar();
        MostrarResultados();
    }//GEN-LAST:event_btejecutarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Traductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Traductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Traductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Traductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Traductor().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTabbedPane Tabbs;
    private javax.swing.JButton btabrir;
    private javax.swing.JButton btcompilar;
    private javax.swing.JButton btcopiar;
    private javax.swing.JButton btejecutar;
    private javax.swing.JButton btguardar;
    private javax.swing.JButton btguardarcomo;
    private javax.swing.JButton btpegar;
    private javax.swing.JTextArea consola;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables
}
